package server

import (
	"fmt"
	"imgscrapy/util"

	"io/ioutil"
	"os"
	"regexp"
	"strconv"
	"strings"
	//	"sync"
)

func Server() {
	URL := os.Getenv("URL")
	PAGE, _ := strconv.Atoi(os.Getenv("PAGE"))
	OUT_PATH := os.Getenv("OUT_PATH")
	RAW := os.Getenv("RAW")
	PLACE := os.Getenv("PLACE")
	PREFIX := os.Getenv("PREFIX")
	SUFFIX := os.Getenv("SUFFIX")
	ATTR := os.Getenv("ATTR")

	ch := make(chan string, 20)
	exit := make(chan int)
	go func() {
		for imgsrc := range ch {

			imgurl := strings.Replace(imgsrc, RAW, ""+PLACE, 1)
			if !strings.Contains(imgurl, "http") {
				imgurl = strings.Replace(imgurl, "//", "https://", 1)
			}

			fmt.Println(imgurl)

			bytes := util.Get(imgurl)
			if strings.Contains(imgurl, "?") {
				imgurl = strings.Split(imgurl, "?")[0]
			}
			if strings.Contains(imgurl, "!") {
				imgurl = strings.Split(imgurl, "!")[0]
			}
			arr := strings.Split(imgurl, "/")
			fmt.Println(arr[len(arr)-1])

			ioutil.WriteFile(OUT_PATH+"/"+arr[len(arr)-1], []byte(bytes), os.ModePerm)
		}
		exit <- -1
	}()

	for i := 1; i <= PAGE; i += 1 {
		page := i

		fullpath := URL
		if PREFIX+SUFFIX != "" {
			fullpath += PREFIX + strconv.Itoa(page) + SUFFIX
		}
		fmt.Println(fullpath)
		html := util.Get(fullpath)
		//fmt.Println(html)
		reg := regexp.MustCompile(`<img[^>]+\b` + ATTR + `=["']([^"']+)["']`)
		imgout := reg.FindAllStringSubmatch(html, -1)
		//fmt.Println(imgout)

		for _, img := range imgout {
			imgsrc := img
			if strings.Contains(imgsrc[1], RAW) {
				ch <- imgsrc[1]
			} else {

			}
		}

	}
	close(ch)
	<-exit

}
